#include <brpc/channel.h>
#include <brpc/controller.h>
#include <google/protobuf/stubs/callback.h>
#include <thread>
#include "main.pb.h"

void callback(brpc::Controller* controller, ::example::EchoResponse* response) {
    if (controller->Failed() == true) {
        std::cout << "rpc调用失败: " << controller->ErrorText() << std::endl;
        return;
    }
    std::cout << "收到响应: " << response->message() << std::endl;
    delete controller;
    delete response;
}

int main()
{
    // 1.构造Channel信道，连接服务器
    // 1-1 设置信道配置项
    brpc::ChannelOptions options;
    options.connect_timeout_ms = -1;    // 连接空闲的超时上限(-1表无限空闲)
    options.timeout_ms = -1;            // rpc请求等待时间(-1无限期等待)
    options.max_retry = 3;              // rpc请求失败后的重试次数
    options.protocol = "baidu_std";     // 序列化协议
    brpc::Channel channel;
    int ret = channel.Init("127.0.0.1:8080", &options);
    if(ret == -1) {
        std::cout << "初始化信道失败\n";
        return 1;
    }
    // 2.构造EchoService_Stub对象，用于rpc调用
    example::EchoService_Stub stub(&channel);
    example::EchoRequest req;
    req.set_message("this is a rpc test.");
    brpc::Controller* controller = new brpc::Controller();
    example::EchoResponse* resp = new example::EchoResponse();
    
    // 2-1 同步调用
    // stub.Echo(controller, &req, resp, nullptr);     
    // if (controller->Failed() == true) {
    //     std::cout << "Rpc调用失败: " << controller->ErrorText() << std::endl;
    //     return -1;
    // }
    // std::cout << "收到响应: " << resp->message() << "\n";
    // delete controller;
    // delete resp;

    // 2-2 异步调用(需设置请)
    google::protobuf::Closure* closure = google::protobuf::NewCallback(callback, controller, resp);
    stub.Echo(controller, &req, resp, closure);
    std::cout << "异步调用结束！\n";
    std::this_thread::sleep_for(std::chrono::seconds(3));       // 等待请求响应完毕
    return 0;
}

